<template>
  <div class="account-management-content" v-if="localStore.innerWidth > 768">
    <div class="management-item f-r-sbc">
      <div class="management-desc">
        <p class="desc-title">登录密码</p>
        <p class="desc-subtitle">已设置</p>
      </div>
      <span class="management-action cursor" @click="edit('setting')">编辑</span>
    </div>
    <div class="management-item f-r-sbc">
      <div class="management-desc">
        <p class="desc-title">绑定手机</p>
        <p class="desc-subtitle">+86 {{ user_info.mobile }}</p>
      </div>
      <span class="management-action cursor" @click="edit('binding')">编辑</span>
    </div>
  </div>

  <!-- 移动 -->
  <div class="account-management-wrap" v-else>
    <div class="common-title-m f-r-dc">
      <div class="back-box f-r-cc cursor" @click="back">
        <el-icon :size="22" color="#111"><Back /></el-icon>
      </div>
      <span>{{ is_details ? current_type == 'setting' ? '登录密码' : '手机号绑定' : '账号与密码' }}</span>
    </div>
    <div class="account-management-content" v-if="!is_details">
      <div class="management-item f-r-sbc" @click="edit('setting')">
        <div class="management-desc">
          <p class="desc-title">登录密码</p>
          <p class="desc-subtitle">已设置</p>
        </div>
        <div class="action-wrap f-r-sbc">
            <span class="management-action cursor">编辑</span>
            <el-icon :size="16" color="#8394AC" class="sidebar-item-right-arrow"><ArrowRight /></el-icon>
        </div>
      </div>
      <div class="management-item f-r-sbc" @click="edit('binding')">
        <div class="management-desc">
          <p class="desc-title">绑定手机</p>
          <p class="desc-subtitle">+86 {{ user_info.mobile }}</p>
        </div>
        <div class="action-wrap f-r-sbc">
            <span class="management-action cursor">编辑</span>
            <el-icon :size="16" color="#8394AC" class="sidebar-item-right-arrow"><ArrowRight /></el-icon>
        </div>
      </div>
    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title=""
    width="560"
    :show-close="false"
    style="padding: 0;"
    custom-class="custom-dialog-container"
    class="account-dialog-container"
  >
    <template #header>
      <div class="dialog-header" v-if="current_type == 'setting'">
        <p class="title">登录密码 - 设置密码</p>
        <p class="subtitle">设置密码后，所有[平台]账号登录密码都会同步设置</p>
      </div>
      <div class="dialog-header" v-if="current_type == 'binding'">
        <p class="title">手机号绑定 - 换绑手机</p>
        <p class="subtitle">换绑手机后，所有[平台]绑定手机号都会同步更换，暂不支持解绑手机号</p>
      </div>
    </template>
    <div class="dialog-content">
      <el-form
        ref="settingFormRef"
        style="width: 100%"
        :model="settingRuleForm"
        :rules="settingRules"
        label-width="120"
        :hide-required-asterisk="true"
        v-if="current_type == 'setting'"
      >
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="settingRuleForm.mobile" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="settingRuleForm.code">
            <template #suffix>
              <span
                class="code-suffix-text cursor"
                @click.stop="
                  getCodeBefore(settingRuleForm.mobile, 'password', 'passwordCodeDisabled','currentTime')
                "
                >{{
                  sms_info.passwordCodeDisabled
                    ? sms_info.countdownText
                    : '获取验证码'
                }}</span
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="重置登录密码" prop="password">
          <el-input v-model="settingRuleForm.password" type="password" />
        </el-form-item>
      </el-form>
      <el-form
        ref="bindingRuleFormRef"
        style="width: 100%"
        :model="bindingRuleForm"
        :rules="bindingRules"
        label-width="120"
        :hide-required-asterisk="true"
        v-if="current_type == 'binding'"
      >
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="bindingRuleForm.mobile" />
        </el-form-item>
        <el-form-item label="验证码" prop="old_code">
          <el-input v-model="bindingRuleForm.old_code">
            <template #suffix>
              <span
                class="code-suffix-text cursor"
                @click.stop="
                  getCodeBefore(bindingRuleForm.mobile, 'old_mobile', 'oldMobileCodeDisabled','oldMobileCurrentTime')
                "
                >{{
                  sms_info.oldMobileCodeDisabled
                    ? sms_info.old_mobile_countdownText
                    : '获取验证码'
                }}</span
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="输入新的手机号" prop="new_phone">
          <el-input v-model="bindingRuleForm.new_phone"> </el-input>
        </el-form-item>
        <el-form-item label="新手机号验证码" prop="code">
          <el-input v-model="bindingRuleForm.code">
            <template #suffix>
              <span
                class="code-suffix-text cursor"
                @click.stop="
                  getCodeBefore(bindingRuleForm.new_phone, 'mobile', 'mobileCodeDisabled','mobileCurrentTime')
                "
                >{{
                  sms_info.mobileCodeDisabled
                    ? sms_info.mobile_countdownText
                    : '获取验证码'
                }}</span
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer f-r-fec">
        <div @click="dialogVisible = false" class="dialog-footer-cancel f-r-cc cursor">取消</div>
        <div type="primary" @click="submit" class="dialog-footer-confirm f-r-cc cursor">提交</div>
      </div>
    </template>
  </el-dialog>

  <!-- 移动 -->
  <div class="form-wrap" v-if="localStore.innerWidth <= 768 && is_details">
    <div class="form-wrap-header" v-if="current_type == 'setting'">
      <p class="title">设置密码</p>
      <p class="subtitle">设置密码后，所有[平台]账号登录密码都会同步设置</p>
    </div>
    <div class="form-wrap-header" v-if="current_type == 'binding'">
      <p class="title">换绑手机</p>
      <p class="subtitle">换绑手机后，所有[平台]绑定手机号都会同步更换，暂不支持解绑手机号</p>
    </div>
    <div class="form-wrap-content">
      <el-form
        ref="settingFormRef"
        style="width: 100%"
        :model="settingRuleForm"
        :rules="settingRules"
        label-width="0"
        :hide-required-asterisk="true"
        v-if="current_type == 'setting'"
      >
        <el-form-item label="" prop="mobile">
          <el-input v-model="settingRuleForm.mobile" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="" prop="code">
          <el-input v-model="settingRuleForm.code" placeholder="请输入验证码">
            <template #suffix>
              <span
                class="code-suffix-text cursor"
                @click.stop="
                  getCodeBefore(settingRuleForm.mobile, 'password', 'passwordCodeDisabled','currentTime')
                "
                >{{
                  sms_info.passwordCodeDisabled
                    ? sms_info.countdownText
                    : '获取验证码'
                }}</span
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input v-model="settingRuleForm.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
      </el-form>
      <el-form
        ref="bindingRuleFormRef"
        style="width: 100%"
        :model="bindingRuleForm"
        :rules="bindingRules"
        label-width="0"
        :hide-required-asterisk="true"
        v-if="current_type == 'binding'"
      >
        <el-form-item label="" prop="mobile">
          <el-input v-model="bindingRuleForm.mobile" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="" prop="old_code">
          <el-input v-model="bindingRuleForm.old_code" placeholder="请输入验证码">
            <template #suffix>
              <span
                class="code-suffix-text cursor"
                @click.stop="
                  getCodeBefore(bindingRuleForm.mobile, 'old_mobile', 'oldMobileCodeDisabled','oldMobileCurrentTime')
                "
                >{{
                  sms_info.oldMobileCodeDisabled
                    ? sms_info.old_mobile_countdownText
                    : '获取验证码'
                }}</span
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="new_phone">
          <el-input v-model="bindingRuleForm.new_phone" placeholder="请输入新的手机号"> </el-input>
        </el-form-item>
        <el-form-item label="" prop="code">
          <el-input v-model="bindingRuleForm.code" placeholder="请输入新手机号验证码">
            <template #suffix>
              <span
                class="code-suffix-text cursor"
                @click.stop="
                  getCodeBefore(bindingRuleForm.new_phone, 'mobile', 'mobileCodeDisabled','mobileCurrentTime')
                "
                >{{
                  sms_info.mobileCodeDisabled
                    ? sms_info.mobile_countdownText
                    : '获取验证码'
                }}</span
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="form-wrap-footer f-r-fec">
      <div type="primary" @click="submit" class="form-wrap-footer-confirm f-r-cc cursor">提交</div>
    </div>
  </div>

  <Verify
    @success="successVerify"
    :captchaType="'blockPuzzle'"
    :imgSize="{ width: '310px', height: '155px' }"
    ref="verifyEl"
  ></Verify>
</template>

<script setup>
import Verify from '@/components/verify/verify.vue'
import { Back, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { sendSms, resetPassword, resetMobile } from '@/api/index.js'
import { useUser } from '@/stores/user'
import { useLocal } from '@/stores/local'

const emits = defineEmits(['back'])

const is_details = ref(false)

const localStore = useLocal()
const dialogVisible = ref(false)

const user_store = useUser()

const current_type = ref('setting')

const verifyEl = ref()

const settingFormRef = ref(null)
const bindingRuleFormRef = ref(null)

//短信校验
const captchaVerification = ref('')

const settingRuleForm = ref({
  mobile: '',
  code: '',
  password: ''
})

const user_info = computed(() => {
  return user_store.user_info
})

const settingRules = ref({
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const bindingRuleForm = ref({
  mobile: '',
  code: '',
  new_phone: '',
  old_code: ''
})

const bindingRules = ref({
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  old_code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  new_phone: [{ required: true, message: '请输入新的手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入新手机号验证码', trigger: 'blur' }]
})

function edit(name) {
  current_type.value = name
  if (localStore.innerWidth > 768) {
    dialogVisible.value = true
  } else {
    is_details.value = true
  }
}

const sms_info = ref({
  codeDisabled: false,
  mobileCodeDisabled: false,
  oldMobileCodeDisabled: false,
  countdownText: '获取验证码',
  old_mobile_countdownText: '获取验证码',
  mobile_countdownText: '获取验证码',
  timer: null,
  old_code_timer: null,
  code_timer: null,
  currentTime: 60,
  oldMobileCurrentTime: 60,
  mobileCurrentTime: 60,
  current_name: ''
})

const current_mobile = ref(null)
const current_disabled_name = ref('codeDisabled')
const current_currentTime_name = ref('currentTime')

function setInterval_ (timer_,text) {
  const currentTime_name = current_currentTime_name.value
  const codeDisabled_name = current_disabled_name.value
  return setInterval(() => {
    sms_info.value[currentTime_name] -= 1
    sms_info.value[text] = `${sms_info.value[currentTime_name]} S`
    if (sms_info.value[currentTime_name] <= 0) {
      clearInterval(timer_)
      sms_info.value[currentTime_name] = 60
      sms_info.value[codeDisabled_name] = false
    }
  }, 1000)
}

function back() {
  if (is_details.value) {
    is_details.value = false
  } else {
    emits('back')
  }
}

function countdown() {
  sms_info.value[current_disabled_name.value] = true
  if (sms_info.value.current_name == 'password') {
    sms_info.value.timer = setInterval_(sms_info.value.timer,'countdownText')
  } else if (sms_info.value.current_name == 'old_mobile') {
    sms_info.value.old_code_timer = setInterval_(sms_info.value.old_code_timer,'old_mobile_countdownText')
  } else if (sms_info.value.current_name == 'mobile') {
    sms_info.value.code_timer = setInterval_(sms_info.value.code_timer,'mobile_countdownText')
  }
}

async function getCode() {
  let res = await sendSms({
    mobile: current_mobile.value,
    event: sms_info.value.current_name,
    captchaVerification: captchaVerification.value
  })
  ElMessage.info(res.msg || '验证码发送成功')
  if (res.msg && res.msg != '滑块验证失败，请重新验证') {
    countdown()
  }
}

// 图形校验成功
const successVerify = (data) => {
  captchaVerification.value = data.captchaVerification
  verifyEl.value.hide()
  getCode()
}

function getCodeBefore(phone, name, disabled_name, currentTime_name) {
  if (sms_info.value[disabled_name]) return
  current_disabled_name.value = disabled_name
  current_currentTime_name.value = currentTime_name
  sms_info.value.current_name = name
  current_mobile.value = phone
  if (!phone) {
    ElMessage.info('请输入手机号')
    return
  }
  verifyEl.value.show()
}

async function submit() {
  if (current_type.value == 'setting') {
    await settingFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        let res = await resetPassword({ ...settingRuleForm.value })
        ElMessage.success('重置成功')
        dialogVisible.value = false
      }
    })
  } else if (current_type.value == 'binding') {
    await bindingRuleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        let { new_phone, code, old_code } = bindingRuleForm.value
        let res = await resetMobile({
          mobile: new_phone,
          code,
          old_code
        })
        if (res.data && Array.isArray(res.data)) {
          ElMessage.info(res.msg)
          return
        }
        user_store.getUserInfoApi()
        ElMessage.success('更换成功')
        dialogVisible.value = false
      }
    })
  }
}
</script>
<style scoped lang="less">
@import './index.less';
@media screen and (max-width: 768px) {
  @import './mobile/index.less';
}
</style>
